<?php
namespace app\common\logic;

use think\facade\Db;
/**
 * 股票
 */
class YiwuTrade
{
    /**
     * 状态
     */
    function getStatus(){
        return array(
            0=>'未打款',
            1=>'完成打款',
            //2=>'超时打款',//迟迟不打款，自动撤销--6
            //3=>'超时匹配',//打款了迟迟不收
            4=>'卖家申诉',//打款了没收到钱
            6=>'已撤销',//后台直接撤销,卖家申诉成功，返给卖家
            7=> '已完成',//确认成功，
        );
    }

    /*
    * 撤单
    * $ids 支持批量
    */
    public function cancel($ids,$desc=''){
        $return = array('status'=>0,'msg'=>'');
        //查询条件
        $map = array(
            'id'=>array('in',$ids),
            'status'=>['lt',6],
        );

        $lists = Db::name('yiwu_trade')->where($map)->field('id,seller_user_id,num,order_no,fee,buyer_user_id,money_type')->select();
        if($lists) {

            foreach ($lists as $list) {
                $result = qianbao($list['seller_user_id'], $list['num']+$list['fee'], $list['money_type'], '交易撤销', $desc . '，匹配单号:' . $list['order_no']);
                if (!$result['status']) {
                    $return['msg'] = '撤销失败：' . $result['msg'];
                    return $return;
                }
            }
            $rs = Db::name('yiwu_trade')->where($map)->update(array( 'status' => 6,'cx_time'=>time()));
            if (!$rs) {
                $return['msg'] = '交易撤销失败：更新状态失败';
                return $return;
            }
        }
        $return['status'] = 1;
        return $return;
    }

    public function confirm($ids,$desc){
        $modtime = time();
        //查询条件
        $map = array(
            'id'=>array('in',$ids),
            'status'=>['lt',6],
        );
        $wallet = logic('Wallet')->getName();

        $lists = Db::name('yiwu_trade')->where($map)->field('id,seller_user_id,num,order_no,fee,buyer_user_id,money_type')->select();
        if($lists) {
            $post = [];
            $post['shoukuan_memo'] = $desc;
            $post['shoukuan_time'] = $modtime;
            $post['status'] = 7;
            $rs = Db::name('YiwuTrade')->whereIn('id', $ids)->update($post);
            if (!$rs) {
                return ['status'=>0,'msg'=>'更新订单状态失败'];
            } else {

                foreach($lists as $info){
                    //给打款人
                    $rs = qianbao($info['buyer_user_id'], $info['num'], $info['money_type'], $wallet[$info['money_type']] . '买入', '单号' . $info['order_no']);
                    if (!$rs['status']) {
                        $rs['msg'] = '更新买家金额失败：'.$rs['msg'];
                        return $rs;
                    }
                }
            }
        }

        return ['status'=>1];
    }

}